package com.wwtech.epp.utils.Image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;

import com.socks.library.KLog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;

/**
 * Tools for handler picture
 * 
 * @author Ryan.Tang
 * 
 */
public final class ImageTools {
	

	
	/**
	 * Save image to the SD card 
	 * @param photoBitmap
	 * @param photoName
	 * @param path
	 */
	public static void savePhotoToSDCard(Bitmap photoBitmap,String path,String photoName){
		if (checkSDCardAvailable()) {
			File photoFile = new File(path , photoName);
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
						fileOutputStream.flush();
					}
				}
			} catch (Exception e) {
				photoFile.delete();
				e.printStackTrace();
			}finally{
				try {
					fileOutputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} 
	}
	
	public static void savePhotoToSDCard(Bitmap photoBitmap,String path){
		if (checkSDCardAvailable()) {
			File photoFile = new File(path);
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
						fileOutputStream.flush();
					}
				}
			} catch (Exception e) {
				photoFile.delete();
				e.printStackTrace();
			} finally{
				try {
					fileOutputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} 
	}
	
	public static void savePhotoToSDCard(Bitmap photoBitmap,String path,Handler handler){
		if (checkSDCardAvailable()) {
			File photoFile = new File(path);
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
						fileOutputStream.flush();
					}
				}
			} catch (Exception e) {
				photoFile.delete();
				e.printStackTrace();
			} finally{
				try {
					fileOutputStream.close();
					handler.sendEmptyMessage(102);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} 
	}
	
	/**
	 * Check the SD card 
	 * @return
	 */
	public static boolean checkSDCardAvailable(){
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}
	
	/**
	 * 
	 * 
	 * @param path
	 *            
	 * @param w
	 *            
	 * @param h
	 *            
	 * @return
	 */
	public static final Bitmap convertToBitmap(String path, int w, int h) {
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			// 
			opts.inJustDecodeBounds = true;
			opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
			// 
			BitmapFactory.decodeFile(path, opts);
			int width = opts.outWidth;
			int height = opts.outHeight;
			float scaleWidth = 0.f, scaleHeight = 0.f;
			if (width > w || height > h) {
				// 
				scaleWidth = ((float) width) / w;
				scaleHeight = ((float) height) / h;
			}
			opts.inJustDecodeBounds = false;
			float scale = Math.max(scaleWidth, scaleHeight);
			opts.inSampleSize = (int) scale;
			WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
			Bitmap bMapRotate = Bitmap.createBitmap(weak.get(), 0, 0, weak.get().getWidth(), weak.get().getHeight(), null, true);
			if (bMapRotate != null) {
				return bMapRotate;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * imagePath: 图片压缩后保存的地址
	 * bitmap: 需要压缩的位图文件
	 * */
	public static void compressImageByQuality(final Bitmap bitmap, final String imgPath , final CallBack callBack){
		if (bitmap == null) {
			return;
		}
	      new Thread(new Runnable() {//开启多线程进行压缩处理
	           @Override
	           public void run() {
	               // TODO Auto-generated method stub
	               ByteArrayOutputStream baos = new ByteArrayOutputStream();
	               int options = 70;
	               bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法，把压缩后的数据存放到baos中 (100表示不压缩，0表示压缩到最小)
	               while (baos.toByteArray().length / 1024 > 500) {//循环判断如果压缩后图片是否大于100kb,大于继续压缩
	                     baos.reset();//重置baos即让下一次的写入覆盖之前的内容
	                     options -= 10;//图片质量每次减少10
	                     if(options<0)options=0;//如果图片质量小于10，则将图片的质量压缩到最小值
	                     bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//将压缩后的图片保存到baos中
	                     if(options==0)break;//如果图片的质量已降到最低则，不再进行压缩
	               }
	               try {
	                     FileOutputStream fos = new FileOutputStream(new File(imgPath));//将压缩后的图片保存的本地上指定路径中
	                     fos.write(baos.toByteArray());
	                     fos.flush();
	                     fos.close();
						 callBack.onSucess();
	               } catch (Exception e) {
						callBack.onFailure();
	                     e.printStackTrace();
	               }
	          }
	     }).start();
	}
	/**
	 * imagePath: 图片压缩后保存的地址
	 * bitmap: 需要压缩的位图文件
	 * */
	public static void compressImageByQualityBroadcast(final String imageName, final Bitmap bitmap, final String imgPath, final CallBackBroadcast callBack){
		if (bitmap == null) {
			return;
		}
	      new Thread(new Runnable() {//开启多线程进行压缩处理
	           @Override
	           public void run() {
	               // TODO Auto-generated method stub
	               ByteArrayOutputStream baos = new ByteArrayOutputStream();
	               int options = 100;
	               bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法，把压缩后的数据存放到baos中 (100表示不压缩，0表示压缩到最小)
	               while (baos.toByteArray().length / 1024 > 500) {//循环判断如果压缩后图片是否大于100kb,大于继续压缩
	                     baos.reset();//重置baos即让下一次的写入覆盖之前的内容
	                     options -= 10;//图片质量每次减少10
	                     if(options<0)options=0;//如果图片质量小于10，则将图片的质量压缩到最小值
	                     bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//将压缩后的图片保存到baos中
	                     if(options==0)break;//如果图片的质量已降到最低则，不再进行压缩
	               }
	               try {
	                     FileOutputStream fos = new FileOutputStream(new File(imgPath));//将压缩后的图片保存的本地上指定路径中
	                     fos.write(baos.toByteArray());
	                     fos.flush();
	                     fos.close();
					   bitmap.recycle();
						 callBack.onSucess(imageName);
	               } catch (Exception e) {
						callBack.onFailure();
	                     e.printStackTrace();
	               }
	          }
	     }).start();
	}
	/**
	 * imagePath: 图片压缩后保存的地址
	 * bitmap: 需要压缩的位图文件
	 * */
	public static void compressImageByQualityDriver(final Bitmap bitmap,final String imgPath ){
	      new Thread(new Runnable() {//开启多线程进行压缩处理
	           @Override
	           public void run() {
	               // TODO Auto-generated method stub
	               ByteArrayOutputStream baos = new ByteArrayOutputStream();
	               int options = 100;
	               bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法，把压缩后的数据存放到baos中 (100表示不压缩，0表示压缩到最小)
	               while (baos.toByteArray().length / 1024 > 500) {//循环判断如果压缩后图片是否大于500kb,大于继续压缩
	                     baos.reset();//重置baos即让下一次的写入覆盖之前的内容
	                     options -= 10;//图片质量每次减少10
	                     if(options<0)options=0;//如果图片质量小于10，则将图片的质量压缩到最小值
	                     bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//将压缩后的图片保存到baos中
	                     if(options==0)break;//如果图片的质量已降到最低则，不再进行压缩
	               }
	               try {
	                     FileOutputStream fos = new FileOutputStream(new File(imgPath));//将压缩后的图片保存的本地上指定路径中
	                     fos.write(baos.toByteArray());
	                     fos.flush();
	                     fos.close();
					  	 KLog.i("图片压缩成功");
	               } catch (Exception e) {
	                     e.printStackTrace();
	               }
	          }
	     }).start();
	}

	public static void compressImageByQuality(final Bitmap bitmap,final String imgPath ,final Handler handler){
	      new Thread(new Runnable() {//开启多线程进行压缩处理
	           @Override
	           public void run() {
	               // TODO Auto-generated method stub
	               ByteArrayOutputStream baos = new ByteArrayOutputStream();
	               int options = 100;
	               bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法，把压缩后的数据存放到baos中 (100表示不压缩，0表示压缩到最小)
	               while (baos.toByteArray().length / 1024 > 100) {//循环判断如果压缩后图片是否大于100kb,大于继续压缩
	                     baos.reset();//重置baos即让下一次的写入覆盖之前的内容
	                     options -= 10;//图片质量每次减少10
	                     if(options<0)options=0;//如果图片质量小于10，则将图片的质量压缩到最小值
	                     bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//将压缩后的图片保存到baos中
	                     if(options==0)break;//如果图片的质量已降到最低则，不再进行压缩
	               }
	               try {
	                     FileOutputStream fos = new FileOutputStream(new File(imgPath));//将压缩后的图片保存的本地上指定路径中
	                     fos.write(baos.toByteArray());
	                     fos.flush();
	                     fos.close();
	                     handler.sendEmptyMessage(100);
	               } catch (Exception e) {
	                     e.printStackTrace();
	               }
	          }
	     }).start();
	}

	/**
	 * @param url
	 * @return
	 * 获取本地的图片转为bitmap
	 */
	public static Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/** 
     * 复制单个文件 
     * @param oldPath String 原文件路径 如：c:/fqf.txt 
     * @param newPath String 复制后路径 如：f:/fqf.txt 
     * @return boolean 
     */ 
   public static void copyFile(String oldPath, String newPath, Handler handler) { 
       try { 
           int bytesum = 0; 
           int byteread = 0; 
           File oldfile = new File(oldPath); 
           if (oldfile.exists()) { //文件存在时 
               InputStream inStream = new FileInputStream(oldPath); //读入原文件 
               FileOutputStream fs = new FileOutputStream(newPath); 
               byte[] buffer = new byte[1444]; 
               int length; 
               while ( (byteread = inStream.read(buffer)) != -1) { 
                   bytesum += byteread; //字节数 文件大小 
                   //System.out.println(bytesum); 
                   fs.write(buffer, 0, byteread); 
               } 
               inStream.close(); 
               handler.sendEmptyMessage(101);
           } 
       } 
       catch (Exception e) { 
           System.out.println("复制单个文件操作出错"); 
           e.printStackTrace(); 

       } 

   }
}
